/*
 * Copyright (c) 2015 xiaofanku
 * mail:xiaofanku@live.cn
 
 * build on jQuery 1.8.1
 * Versions
 * 0.1.2 - 20150409
 *
*/
(function($){
        'use strict';
        $.apoDialog=(function(){
                //全局属性
                var 
                overlayZIndex=9999,
                eleClassPrefix='dialog';
                
                //方法
                var 
                _setIndex,_setPrefix,_uriAction,_bodyAction,_alertAction,_init,getVarType,_closeAction,initDialogHandler,closeDialogHandler,_beforeInit;
                //全局默认参数
                var
                commonConfig={isClosed:false,title:undefined,tip:undefined,redirect:undefined,onOk:null,onCancel:null},
                initbtns={ok:'ok',cancel:'cancel'};
                //限制的参考
                var 
                allowAction='uri,body,alert',
                cssclass='overlay,header,main,footer,closed'.split(',');
                //增加延迟控制
                var defObj=$.Deferred();
                //设置窗口的z-index
                _setIndex=function(zIndex){
                        overlayZIndex=zIndex;
                        return this;
                };
                //设置窗口的样式定义前缀
                _setPrefix=function(classPrefix){
                        eleClassPrefix=classPrefix;
                        return this;
                };
                //设置窗口DOM结构构造结束时初始化处理器
                initDialogHandler=function(handler){
                        $(document).one('dialogInit',handler);
                        return this;
                };
                //设置窗口关闭时的处理器
                closeDialogHandler=function(handler){
                        $(document).one('dialogClose',handler);
                        return this;
                };
                getVarType=function(data) {
                        if(data === undefined){ return 'Undefined'; }
                        if(data === null) { return 'Null'; }
                        return {}.toString.call(data).slice(8,-1);
                };
                _init=function(config){
                        _beforeInit();
                        var eleDialog=null;
                        if(!!config.isBody){
                                //已有元素
                                eleDialog=$(config.container).show();
                        }else{
                                //新添dom
                                var baseEle='<div id="%E%">'.replace('%E%',config.container).replace('#','');
                                if(config.title!==undefined){ baseEle+='<p>%T%</p>';}
                                if(config.tip!==undefined){ baseEle+='<div>%C%</div>';}
                                if(config.redirect!==undefined || config.isBtn){
                                        baseEle+='<p class="%P%_footer"><a data-action="ok" href="javascript:;">%Y%</a><a data-action="cancel" href="javascript:;">%N%</a></p>';
                                }
                                if(config.isClosed){ baseEle+='<em data-action="close" class="%P%_closed">close</em>';}
                                baseEle+='</div>';
                                eleDialog=$(baseEle
                                                .replace('%T%',config.title)
                                                .replace('%C%',config.tip)
                                                .replace('%Y%',initbtns.ok)
                                                .replace('%N%',initbtns.cancel)
                                                .replace(/%P%/g,eleClassPrefix)
                                ).appendTo('body');
                        }
                        if(eleDialog.length==0){ defObj.reject();}
                        //参数为当前窗口的jquery对象,可以在处时器中增加对窗口对像的更多控制
                        $(document).trigger('dialogInit',[eleDialog]);
                        eleDialog
                                .addClass(eleClassPrefix)
                                .css({width:!config.isBody?'auto':eleDialog.css('width'),
                                        height:!config.isBody?'auto':eleDialog.css('height'),
                                        zIndex:parseInt(overlayZIndex)+1,
                                        top:function(){
                                                var msh=parseInt($(window).height());
                                                var ebh=parseInt(eleDialog.outerHeight(true));
                                                return Math.floor(msh/2-ebh/2);
                                        },
                                        left:function(){
                                                var msw=parseInt($(window).width());
                                                var ebw=parseInt(eleDialog.outerWidth(true));
                                                return Math.floor(msw/2-ebw/2);
                                        }
                                });
                        //右上角的图标[X]
                        eleDialog.find('em[data-action=close]').on('click',_closeAction);
                        //点击确认后
                        eleDialog.find('a[data-action=ok]').on('click',function(){
                                if(config.onOk!==null && $.isFunction(config.onOk)){
                                        config.onOk.apply(eleDialog);
                                }
                                var extJS=(config.redirect!==undefined)?'window.location.replace("{URI}");'.replace('{URI}',config.redirect):undefined;
                                _closeAction(extJS);
                        });
                        //点击取消后
                        eleDialog.find('a[data-action=cancel]').on('click',function(){
                                if(config.onCancel!==null && $.isFunction(config.onCancel)){ config.onCancel.apply(eleDialog);}
                                _closeAction();
                        });
                        //设置关闭窗口的事件
                        //点击其它元素(窗口以外的)关闭窗口
                        $(document).bind("click touchstart",function(e){
                                e.stopPropagation();
                                if($(e.target).parents(config.container).length==0){
                                        _closeAction();
                                }
                        });
                        defObj.resolve();
                };
                _uriAction=function(option,findElement,data){
                        var localConfig=commonConfig;
                        $.get(option.redirect,data,function(responseData){
                                var resHtml=$(responseData).find(findElement).html();
                                if(resHtml===undefined){ return _alertAction('loading data fail');}
                                localConfig.tip=resHtml;
                                localConfig.isBody=false;
                                localConfig.container='#apoDialog';
                                localConfig.isBtn=false;
                                //不希望出现按钮
                                option.redirect=undefined;
                                _init($.extend(localConfig, option));
                                  
                        },'html');
                        return defObj.promise();
                };
                _bodyAction=function(option){
                        var localConfig=commonConfig;
                        //附加参数
                        localConfig.isBody=true;
                        var pc=getVarType(option);
                        if(pc==='Object' && option.container){ localConfig.container=option.container;}
                        if(pc==='String'){ localConfig.container=option;}
                        if($(localConfig.container).length>0){ _init(localConfig);}
                        return defObj.promise();
                };
                _alertAction=function(option,buttons){
                        var localConfig=commonConfig;
                        localConfig.isBody=false;//可以不附加
                        localConfig.container='#apoDialog';
                        //buttons
                        if(getVarType(buttons)==='Object' && buttons.ok && buttons.cancel){
                                initbtns.ok=buttons.ok;
                                initbtns.cancel=buttons.cancel
                                localConfig.isBtn=true;
                        }
                        var pc=getVarType(option);
                        //是否是字符串
                        if(pc==='String'){ _init($.extend(localConfig, {tip:option}));}
                        if(pc==='Object'){ _init($.extend(localConfig, option));}
                        return defObj.promise();
                };
                //关闭窗口的事件:close,其它(窗口以外的),ok处理完后
                _closeAction=function(extJS){
                        //窗口
                        var self=$('.'+eleClassPrefix).remove();
                        //底层蒙板
                        $('.'+eleClassPrefix+'_'+cssclass[0]).remove();
                        if(getVarType(extJS)=='String'){ eval(extJS);}
                        if($.isFunction(extJS)){ extJS();}
                        $(document).trigger('dialogClose',[self]);
                };
                //前期处理:是否已经有dialog存在了
                _beforeInit=function(){
                    var fullClass=eleClassPrefix+'_'+cssclass[0];
                    //不存在
                    if(!($('.'+fullClass).length>0)){
                        $('<div/>').addClass(fullClass).css({'zIndex':overlayZIndex}).appendTo('body');
                        return;
                    }
                    //存在
                    var dialogEle=$('.'+eleClassPrefix);
                    if(dialogEle.css('width')=='auto'){
                        //新建的DOM结构
                        dialogEle.remove();
                    }else{
                        //document中原有的
                        dialogEle.hide();
                    }
                };
                return {
                        setZIndex:_setIndex,
                        setCSSClassPrefix:_setPrefix,
                        uri:_uriAction,
                        body:_bodyAction,
                        alert:_alertAction,
                        init:initDialogHandler,
                        clear:closeDialogHandler,
                        close:_closeAction
                };
        }());
}(jQuery));
